<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(item, index) in list"
      :key="index"
      icon="search"
      @click="$emit('search',item)"
    >
       <div v-html="highlight(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from "@/api/search";
import { debounce } from "lodash";
// debounce(函数，防抖时间)  ==> 返回防抖函数
export default {
  name: "SearchSuggestion",
  data() {
    return {
      list: [] // 搜索建议
    };
  },
  props: {
    // 搜索关键字
    searchText: {
      type: String,
      require: true
    }
  },
  watch: {
    searchText: {
      immediate: true, // 一开始就执行一次
      handler(){
         this.loadSuggestion()
      }
    }
  },
  methods: {
    //节流函数
    loadSuggestion:debounce(async function(){
        try {
          let { data:res } = await getSearchSuggestion(this.searchText)
          this.list = res.data.options

        } catch (error) {
          this.$toast.fail('获取联想建议失败')
        }
    },1000),
    // 高亮处理函数
    highlight(val){
      // 定义正则
      const reg = new RegExp(this.searchText, 'gi')
      return val.replace(reg,`<span style="color:red">${this.searchText}</span>`)
    }
  }
};
</script>

<style scoped lang="less"></style>
